import { writeFile } from "fs/promises";
import { join } from "path";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { fileName, content } = body;

    // 确保文件名和内容存在
    if (!fileName || !content) {
      throw new Error("文件名和内容不能为空");
    }

    // 构建文件路径
    const filePath = join(process.cwd(), "content/blog", fileName);

    // 写入文件
    await writeFile(filePath, content, "utf-8");

    return {
      success: true,
      message: "文章发布成功",
    };
  } catch (error) {
    console.error("发布文章失败:", error);
    throw createError({
      statusCode: 500,
      message: "发布文章失败",
    });
  }
});
